package com.mzl.lal4cloud.lxw4rf.service.contract.http;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.mzl.lal4cloud.lxw4rf.service.contract.bean.ErrorResult;
import com.mzl.lal4cloud.lxw4rf.service.contract.bean.HeaderConfig;
import com.mzl.lal4cloud.lxw4rf.service.contract.common.Consts;
import com.mzl.lal4cloud.lxw4rf.service.contract.exception.ErrorException;
import com.mzl.lal4cloud.lxw4rf.service.contract.http.okhttp.OkHttpSimplePostRequestExecutor;
import com.mzl.lal4cloud.lxw4rf.service.contract.util.MD5Utils;
import com.mzl.lal4cloud.lxw4rf.service.contract.util.RSAUtils;
import okhttp3.Headers;
import okhttp3.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import java.io.IOException;
import java.util.Base64;
import java.util.Objects;

/**
 * 简单的POST请求执行器，请求的参数是String, 返回的结果也是String
 *
 * @author J_luo
 */
public abstract class SimplePostRequestExecutor<H, P> implements RequestExecutor<String, String> {

    public Logger logger = LoggerFactory.getLogger(this.getClass());

    protected RequestHttp<H, P> requestHttp;

    public SimplePostRequestExecutor(RequestHttp requestHttp) {
        this.requestHttp = requestHttp;
    }

    @Override
    public void execute(String uri, String data, ResponseHandler<String> handler)
            throws Exception {
        handler.handle(this.execute(uri, data));
    }

    public static RequestExecutor<String, String> create(RequestHttp requestHttp) {
        switch (requestHttp.getRequestType()) {
            case OK_HTTP:
                return new OkHttpSimplePostRequestExecutor(requestHttp);
            default:
                throw new IllegalArgumentException("非法请求参数");
        }
    }

    public String handleResponse(Response response) throws ErrorException, IOException {

        if (response.headers().get("Content-Type").equals("application/zip") || response.headers().get("Content-Type").equals("application/pdf")) {
            return Base64.getEncoder().encodeToString(response.body().bytes());
        }
        String responseContent = Objects.requireNonNull(response.body()).string();
        if (responseContent.isEmpty()) {
            throw new ErrorException("无响应内容");
        }
        ErrorResult error = ErrorResult.fromJson(responseContent);
        if (!error.isSuccess()) {
            logger.error("调用远程接口失败！ 内容： {}", responseContent);
            throw new ErrorException(error);
        }
        return responseContent;
    }

    /**
     * 获取请求头
     *
     * @param uriWithParam
     * @param requestData
     * @return
     * @throws Exception
     */
    protected Headers getHeaders(String uriWithParam, Object requestData) throws ErrorException {
        HeaderConfig headerConfig = requestHttp.getHeaderConfig();
        Headers headers = new Headers
                .Builder()
                .add("Content-type","application/json")
                .add("Authorization", headerConfig.getAuthorization())
                .add("bestsign-sign-timestamp", headerConfig.getBestsignSignTimestamp().toString())
//                .add("bestsign-sign-timestamp","1610868982204")
                .add("bestsign-client-id", headerConfig.getBestsignClientId())
                .add("bestsign-signature-type", "RSA256")
                .add("bestsign-signature", this.signRequest(uriWithParam, requestData, headerConfig))
//                .add("bestsign-signature","Z1MSxlDUcufHFGtVH%2fcZSLVoa5LpHYd3bcD96g9LH8RwGy%2bTUGQ%2bSudUvDBcuAu1W%2burYg5OEEr%2bHy13apgnAhPKtFrZ%2bCDaRawDDnk3YTZhbxr0C59b6%2bABgjLj3Af1LhSRv%2bdcAti314K2YdQ4V8ZLI1wnLMszjh6Yv1bdBuuGaSSMiq5DFPnHvqV%2bQe%2bXmA1FQjRETjFIHz%2ftI3XGs8mKXMF2dzHM6aF9jP3fHkYuzMzWF4ruB4UFL8LHv8H541VlvaU5Ys9rBx9e74lVQr15oN5R2YIWg5glHcO9aQN1PNDWUcZnjFwxKMr3hldBWM6o%2fbj8JVhtDXSj%2fkty%2bw%3d%3d")
                .build();
        return headers;
    }


    private String signRequest(String uriWithParam, Object requestData, HeaderConfig headerConfig) throws ErrorException {
        try {
            String content = String.format(
                    Consts.BEST_URI,
                    headerConfig.getBestsignClientId(),
                    headerConfig.getBestsignSignTimestamp().toString(),
                    "RSA256",
                    MD5Utils.stringMD5(requestData == null ? "" : requestData.toString()),
                    uriWithParam.replace(headerConfig.getHostUri(), ""));

            return RSAUtils.signRSA(content, headerConfig.getPrivateKey());
        }catch (Exception e) {
            throw new ErrorException("加密错误！");
        }
    }
}
